package MTT::Libs::ObjectAccess;

use base 'Class::Singleton';

use MTT::Schema;

use Data::Dumper;

sub check_objects_access {
	my ($self, $c, $type_name, $id) = @_;

	my $type = $c->model('DBIC::ObjectType')->search({name => $type_name})->next();

	unless ( $type ) {
		die "Invalid type object $type_name";
	}	
	
	my $access = $c->model('DBIC::AccessObject')->find({
			id 	=> $id,
			object_type => $type->id,
			id_user		=> $c->user->id
		});

	return $access ? 1 : 0;
}

sub permitted_objects {
	my ($self, $c, $type_name) = @_;

	my $type = $c->model('DBIC::ObjectType')->search({name => $type_name})->next();
	unless ( $type ) {
		die "Invalid type object $type_name";
	}	
	
	my $schema = $c->model('DBIC')->schema();
	return $schema->storage->dbh_do( 
		sub {
			my ($storage, $dbh, $object_type, $id_user) = @_;
			return $dbh->selectall_arrayref(
				'SELECT id FROM access_object where object_type = ? and id_user = ?',
				undef,
				$object_type,
				$id_user
			);
		},
		$type->id, 
		$c->stash->{id_user}
	);
}

sub unpermitted_objects {
	my ($self, $c, $type_name) = @_;

	my $type = $c->model('DBIC::ObjectType')->search({name => $type_name})->next();
	unless ( $type ) {
		die "Invalid type object $type_name";
	}	
	
	my $schema = $c->model('DBIC')->schema();
	return $schema->storage->dbh_do( 
		sub {
			my ($storage, $dbh, $object_type, $id_user) = @_;
			return $dbh->selectall_arrayref(
				'SELECT s.id FROM switch_type s'
			   	. ' WHERE NOT EXISTS ('
				. ' SELECT * FROM access_object a WHERE s.id = a.id AND a.object_type = ? AND id_user = ?'
				. ')',
				undef,
				$object_type,
				$id_user
			);
		},
		$type->id, 
		$c->stash->{id_user}
	);
}


1;
